﻿/***********************************************************
 * DavidLee 2019/11/17
 * NetCoreCMS-后端调用规范：
 *  1：前端页面渲染（MVC）模式调用，在Controller里编写
 *  2: 前端页面ajax Post模式调用，在ApiController里编写
 * 
 ***********************************************************/
using CleanArchitecture.Core.Configuration;
using CleanArchitecture.Core.Handlers;
using CleanArchitecture.Infrastructure.Entities.Settings;
using CleanArchitecture.Infrastructure.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace ClientApp.Web.Api
{
    [Route("api/[controller]")]
    [ApiController]
    public abstract class BaseApiController : Controller
    {
        #region Ajax Response for HttpPost
        protected virtual IActionResult SuccessJson(string message)
        {
            return Json(new { state = NotifyType.Success, message = message });
        }
        protected virtual IActionResult SuccessJson(string message, object data)
        {
            return Json(new { state = NotifyType.Success, message = message, data = data });
        }
        protected virtual IActionResult WarnJson(string message)
        {
            return Json(new { state = NotifyType.Warning, message = message });
        }
        protected virtual IActionResult ErrorJson(string message)
        {
            return Json(new { state = NotifyType.Error, message = message });
        }
        protected virtual IActionResult PageNotFoundJson(string message)
        {
            return Json(new { state = NotifyType.NotFound404, message = message });
        }
        protected virtual IActionResult RedirectJson(string message, object data)
        {
            return Json(new { state = NotifyType.RedirectUrl, message = message, data = data });
        }

        #endregion

        /// <summary>
        /// Creates an object that serializes the specified object to JSON.
        /// </summary>
        /// <param name="data">The object to serialize.</param>
        /// <returns>The created object that serializes the specified data to JSON format for the response.</returns>
        public override JsonResult Json(object data)
        {
            var serializerSettings = GetJsonSerializerSettings();
            return base.Json(data, serializerSettings);
        }

        public virtual JsonSerializerSettings GetJsonSerializerSettings()
        {
            var useIsoDateFormat = EngineContext.Current.Resolve<AdminAreaSettings>()?.UseIsoDateFormatInJsonResult ?? false;
            var serializerSettings = EngineContext.Current.Resolve<IOptions<MvcNewtonsoftJsonOptions>>()?.Value?.SerializerSettings
                ?? new JsonSerializerSettings();

            if (!useIsoDateFormat)
                return serializerSettings;

            serializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
            serializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Unspecified;
            return serializerSettings;
        }

        /// <summary>
        /// Creates an object that serializes the specified object to JSON
        /// Used to serialize data for DataTables
        /// </summary>
        /// <typeparam name="T">Model type</typeparam>
        /// <param name="model">The model to serialize.</param>
        /// <returns>The created object that serializes the specified data to JSON format for the response.</returns>
        public JsonResult Json<T>(BasePagedListModel<T> model) where T : BaseEntityModel
        {
            return Json(new
            {
                recordsTotal = model.RecordsTotal,
                recordsFiltered = model.RecordsFiltered,
                data = model.Data,
            });
        }
    }
}
